package com.fancy.learncenter.activity;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.transition.Transition;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.adapter.PingLunAdapter;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.CommentsDataBean;
import com.fancy.learncenter.bean.TopDataBean;
import com.fancy.learncenter.bean.TrainListDataBean;
import com.fancy.learncenter.common.SampleListener;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.DimenUtil;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.fancy.learncenter.view.LPopWindow;
import com.fancy.learncenter.view.PopupWindowSendDiscuss;
import com.fancy.learncenter.view.PopupWindowShare;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.CustomGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.superservice.lya.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 单独的视频播放页面
 * Created by shuyu on 2016/11/11.
 */
public class MaterialVideoDetailActivity extends BaseActivity {
    public final static String IMG_TRANSITION = "IMG_TRANSITION";
    public final static String TRANSITION = "TRANSITION";
    @Bind(R.id.video_player)
    CustomGSYVideoPlayer videoPlayer;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.zan)
    ImageView zan;
    @Bind(R.id.rl_send)
    RelativeLayout rlSend;
    @Bind(R.id.rootView)
    RelativeLayout rootView;

    private String vedioId;
    public static String VEDIO_KEY = "VEDIO_KEY";


    private Transition transition;
    OrientationUtils orientationUtils;


    View topView;


    TrainListDataBean trainListDataBean;

    private boolean discussTz = true;

    private String commentId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail, getResources().getColor(R.color.toolbar_color));
        ButterKnife.bind(this);
//        trainListDataBean = (TrainListDataBean) getIntent().getSerializableExtra(VEDIO_KEY);

        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.GONE);

        vedioId = getIntent().getStringExtra(VEDIO_KEY);

        getDatas();


        popupWindowSendDiscuss = new PopupWindowSendDiscuss(this, recycleView);

        popupWindowSendDiscuss.setSendDisCallBack(new PopupWindowSendDiscuss.SendDisCallBack() {
            @Override
            public void sendDiscuss() {

                if (Utils.isFastClick()) {
                    if (discussTz) {
                        tZComment();
                    } else {
                        tZCommentReply();
                    }
                }

            }
        });

        rlSend.setVisibility(View.GONE);
    }

    PingLunAdapter discussAdapter;

    PopupWindowSendDiscuss popupWindowSendDiscuss;
    TextView video_title;
    TextView play_num;
    TextView name;
    TextView time;
    TextView follow;
    TextView praise_num;
    ImageView share_img;
    SimpleDraweeView user_icon;
    LinearLayout discuss_ll;

    PopupWindowShare popupWindowShare;

    String shareUrlPic = "";
    String shareLinkUrl = "";
    String shareTitle = "";
    String shareContent = "";

    private void init(String urlPath) {
        topView = LayoutInflater.from(this).inflate(R.layout.activity_video_detail_top, null);

        discuss_ll = topView.findViewById(R.id.discuss_ll);
        discuss_ll.setVisibility(View.GONE);

        user_icon = (SimpleDraweeView) topView.findViewById(R.id.user_icon);
        user_icon.setImageURI(trainListDataBean.getImgsrc());

        video_title = (TextView) topView.findViewById(R.id.video_title);
        video_title.setText(trainListDataBean.getTitle());


        play_num = (TextView) topView.findViewById(R.id.play_num);
        play_num.setText(trainListDataBean.getPlayed_num());


        name = (TextView) topView.findViewById(R.id.name);
        name.setText(trainListDataBean.getAuthor());


        time = (TextView) topView.findViewById(R.id.time);
        time.setText(trainListDataBean.getAdd_time());


        play_num = (TextView) topView.findViewById(R.id.play_num);
        if (!TextUtils.isEmpty(trainListDataBean.getPlayed_num())) {
            play_num.setText(trainListDataBean.getPlayed_num() + "次播放");
        }


        share_img = topView.findViewById(R.id.share_img);
        share_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindowShare == null) {
                    popupWindowShare = new PopupWindowShare(MaterialVideoDetailActivity.this, rootView);
                    popupWindowShare.setOnClickCallBack(new PopupWindowShare.OnClickCallBack() {
                        @Override
                        public void wxFriendCallBack() {
                            WXShareUtil.getInstance(MaterialVideoDetailActivity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, true);
                        }

                        @Override
                        public void wxCallBack() {
                            WXShareUtil.getInstance(MaterialVideoDetailActivity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, false);
                        }
                    });
                }
                popupWindowShare.showAtLocation();
            }
        });


        praise_num = (TextView) topView.findViewById(R.id.praise_num);
        praise_num.setText(trainListDataBean.getTop_num() + "");
        praise_num.setVisibility(View.GONE);

        follow = (TextView) topView.findViewById(R.id.follow);
        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

//
//        VideoOptionModel videoOptionModel =
//                new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 50);
//        List<VideoOptionModel> list = new ArrayList<>();
//        list.add(videoOptionModel);
//
//        GSYVideoManager.instance().setOptionModelList(list);
        //需要路径的
        videoPlayer.setUp(urlPath, true, "");
        //增加封面
        SimpleDraweeView imageView = new SimpleDraweeView(this);

        GenericDraweeHierarchy hierarchy = imageView.getHierarchy();
        hierarchy.setPlaceholderImage(R.mipmap.small);
        hierarchy.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER);
        imageView.setHierarchy(hierarchy);
        imageView.setImageURI(trainListDataBean.getImgsrc());
        videoPlayer.setThumbImageView(imageView);

        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.GONE);

        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.GONE);

        videoPlayer.getBackButton().setImageResource(R.mipmap.ic_fanhui);


        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        videoPlayer.setIsTouchWiget(true);
        //关闭自动旋转
        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(false);
        videoPlayer.setShowFullAnimation(false);
        videoPlayer.setNeedLockFull(true);


        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        videoPlayer.getFullscreenButton().setVisibility(View.VISIBLE);
//

        videoPlayer.setStandardVideoAllCallBack(new SampleListener() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                //开始播放了才能旋转和全屏
                orientationUtils.setEnable(true);
                isPlay = true;
            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
            }

            @Override
            public void onClickStartError(String url, Object... objects) {
                super.onClickStartError(url, objects);
            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                if (orientationUtils != null) {
                    orientationUtils.backToProtVideo();
                }
            }
        });
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //直接横屏
                orientationUtils.resolveByClick();
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                videoPlayer.startWindowFullscreen(MaterialVideoDetailActivity.this, true, true);
//                orientationUtils.resolveByClick();
            }
        });

        videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress));
        videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress));
        videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg));
        videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress));
        videoPlayer.setDialogProgressColor(getResources().getColor(R.color.yellow), getResources().getColor(R.color.white));

        videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress),
                getResources().getDrawable(R.drawable.video_new_seekbar_thumb));
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);

//        videoPlayer.startPlayLogic();
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        videoPlayer.setLockLand(true);
        //过渡动画


        ArrayList discussDatas;
        discussDatas = new ArrayList<>();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);
        discussAdapter = new PingLunAdapter(this, discussDatas);
        recycleView.setAdapter(discussAdapter);
        discussAdapter.setHeaderView(topView, recycleView);

        discussAdapter.setOnClickCallBack(new PingLunAdapter.OnClickCallBack() {
            @Override
            public void OnClick(int position) {
                discussTz = false;

                commentId = listDataBean.get(position).getId();

                popupWindowSendDiscuss.showPop();
            }
        });

    }


    @Override
    public void finish() {
        super.finish();
        if (orientationUtils != null)
            orientationUtils.releaseListener();

        if (videoPlayer != null) {

            videoPlayer.onVideoPause();

            videoPlayer.onVideoReset();

            videoPlayer = null;

        }
    }

    //分享弹出框
    LPopWindow lPopWindow;

    private void initPicPopWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pupopwinodw_share, null);
        TextView cancel = (TextView) contentView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lPopWindow.dismiss();
            }
        });
        TextView weixin = (TextView) contentView.findViewById(R.id.weixin);
        weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show("微信");
            }
        });
        TextView quan = (TextView) contentView.findViewById(R.id.quan);
        quan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show("朋友圈");
            }
        });
        TextView qq = (TextView) contentView.findViewById(R.id.qq);
        qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show("微信");
            }
        });
        TextView zone = (TextView) contentView.findViewById(R.id.zone);
        zone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show("朋友圈");
            }
        });
        lPopWindow = new LPopWindow.Builder(MaterialVideoDetailActivity.this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dip2px(200))
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .build()
                .showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }


    @Override
    protected void onPause() {
        super.onPause();
        isPause = true;
        if (videoPlayer != null) {
            videoPlayer.onVideoPause();
        }

//        GSYPreViewManager.instance().getMediaPlayer().pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isPause = false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }

    private void getDatas() {
        Map map = new HashMap();
        map.put("videoId", vedioId + "");
        HttpMehtod.getInstance().materialVideoDetail(map, new IdeaObserver<BaseDataBean<TrainListDataBean>>(this, true) {

            @Override
            public void onSuccess(BaseDataBean<TrainListDataBean> listBaseDataBean) {
                trainListDataBean = listBaseDataBean.getData();

                topNum = listBaseDataBean.getData().getTop_num();


                if (trainListDataBean.getIs_top() == 0) {

                    zan.setImageResource(R.mipmap.ic_zan);

                } else {

                    zan.setImageResource(R.mipmap.ic_zan_s);

                }


                 shareUrlPic = listBaseDataBean.getData().getShare_img();
                 shareLinkUrl = listBaseDataBean.getData().getShare_link();
                 shareTitle = listBaseDataBean.getData().getShare_title();
                 shareContent = listBaseDataBean.getData().getShare_content();

                init(listBaseDataBean.getData().getSite());


                tzCommenLists();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    int topNum = 0;

    private void zan() {
        Map map = new HashMap();
        map.put("videoId", vedioId + "");


        HttpMehtod.getInstance().videoTop(map, new IdeaObserver<BaseDataBean<TopDataBean>>(this, true) {


            @Override
            public void onSuccess(BaseDataBean<TopDataBean> topDataBeanBaseDataBean) {

                String status = topDataBeanBaseDataBean.getData().getStatus();
                if (status.equals("top")) {
                    topNum++;
                    praise_num.setText(topNum + "");
                    zan.setImageResource(R.mipmap.ic_zan_s);
                } else {
                    topNum--;
                    praise_num.setText(topNum + "");
                    zan.setImageResource(R.mipmap.ic_tw_zan);
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }


    @OnClick({R.id.zan, R.id.share, R.id.send_tv, R.id.back_icon, R.id.activity_play})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_icon:
                finish();
                break;
            case R.id.zan:

                zan();
                break;
            case R.id.share:
                initPicPopWindow(view);
                break;
            case R.id.send_tv:
                discussTz = true;
                popupWindowSendDiscuss.showPop();
                break;
            case R.id.activity_play:
                break;
        }
    }


    private void tZComment() {
        Map map = new HashMap();
        map.put("videoId", trainListDataBean.getId());
        map.put("content", popupWindowSendDiscuss.getDiscuss());

        HttpMehtod.getInstance().videoComment(map, new IdeaObserver<BaseDataBean>() {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {
                tzCommenLists();

                ToastUtil.show("评论成功");
                popupWindowSendDiscuss.dismiss();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void tZCommentReply() {
        Map map = new HashMap();
        map.put("forumId", trainListDataBean.getId());
        map.put("content", popupWindowSendDiscuss.getDiscuss());
        map.put("commentId", commentId);

        HttpMehtod.getInstance().tZCommentReply(map, new IdeaObserver() {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {

                ToastUtil.show("评论成功");
                popupWindowSendDiscuss.dismiss();
                tzCommenLists();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    List<CommentsDataBean> listDataBean = new ArrayList<>();

    private void tzCommenLists() {
        Map map = new HashMap();
        map.put("videoId", trainListDataBean.getId() + "");

        HttpMehtod.getInstance().trainCommentLists(map, new IdeaObserver<BaseDataBean<List<CommentsDataBean>>>() {

            @Override
            public void onSuccess(BaseDataBean<List<CommentsDataBean>> listBaseDataBean) {

                if (listBaseDataBean.getData() != null) {

                    listDataBean = listBaseDataBean.getData();
                    discussAdapter.notifyDataSetChanged((ArrayList<CommentsDataBean>) listBaseDataBean.getData());
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }


    @Override
    public void onBackPressed() {


        if (orientationUtils != null && orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {

            //直接横屏
            orientationUtils.resolveByClick();
//            videoPlayer.getBackButton().performClick();
//            videoPlayer.getFullscreenButton().performClick();
            LogUtil.MyLog("onBackPressed", "======onBackPressed===" + orientationUtils.getScreenType());
            return;
        }

        if (videoPlayer != null) {
            //释放资源
            videoPlayer.setStandardVideoAllCallBack(null);
            GSYVideoPlayer.releaseAllVideos();
        }


        super.onBackPressed();
    }

    private boolean isPlay;
    private boolean isPause;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_USER) {
                if (!videoPlayer.isIfCurrentIsFullscreen()) {
                    videoPlayer.startWindowFullscreen(MaterialVideoDetailActivity.this, true, true);
                }
            } else {
                //新版本isIfCurrentIsFullscreen的标志位内部提前设置了，所以不会和手动点击冲突
                if (videoPlayer.isIfCurrentIsFullscreen()) {
                    StandardGSYVideoPlayer.backFromWindowFull(this);
                }
                if (orientationUtils != null) {
                    orientationUtils.setEnable(true);
                }
            }
        }


    }

}
